# Virtual Router Simulator 
#
# Copyright (C) 2009-2010 VRSim Project
# Author: Choonho Son <choonho@kt.com>
# URL: <http://vrsim.googlecode.com>
# For license information, see LICENSE.TXT
#

import VRSim.Globals as globals
import datetime
import copy
import os
import re
from PyQt4 import QtGui,  QtCore
from VRSim.Ui.Ui_Config import Ui_Config
from VRSim.Ui.RemoteFolder import RemoteFolder

from VRSim.Node.Router import Router
from VRSim.Node.Cisco import Cisco
#from VRSim.Node.Domain import Domain
#from VRSim.Node.CiscoDomain import CiscoDomain
from VRSim.Node.Interface import Interface
from VRSim.Utils import debug,  message

class Config(QtGui.QDialog,  Ui_Config):
    def __init__(self,  pnode,  page="General"):
        QtGui.QDialog.__init__(self)
        Ui_Config.__init__(self)
        self.pnode = copy.copy(pnode)
        self.isCisco = False
        
        # FLAGS
        self.changeSummary = False # update summary window, {hostname, isVirtual}
        self.changeHostname = False
        
        # translation
        title0 = QtGui.QApplication.translate("Config",  "General Configurations of Node",  None,  QtGui.QApplication.UnicodeUTF8)
        title1 = QtGui.QApplication.translate("Config",  "HardDisk Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        title2 = QtGui.QApplication.translate("Config",  "CD/DVD-ROM Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        title3 = QtGui.QApplication.translate("Config",  "Floopy Disk Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        title4 = QtGui.QApplication.translate("Config",  "Audio Device Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        title5 = QtGui.QApplication.translate("Config",  "Network Device Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        title6 = QtGui.QApplication.translate("Config",  "Serial Port Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        title7 = QtGui.QApplication.translate("Config",  "Video Device Configuration",  None,  QtGui.QApplication.UnicodeUTF8)
        
        self.setupUi(self)
        self.item = ["General",  "HardDisk",  "CD/DVD-ROM",  "Floopy",  "Audio",  "Network",  "Serial Port",  "Video"]
        self.itemIcon = {"General": ":/symbols/config/general.png",  
                                "HardDisk": ":/symbols/config/harddisk.png", 
                                "CD/DVD-ROM" : ":/symbols/config/cdrom.png", 
                                "Floopy" : ":/symbols/config/floopy.png", 
                                "Audio" : ":/symbols/config/sound.png", 
                                "Network": ":/symbols/config/network.png", 
                                "Serial Port" : ":/symbols/config/serialport.png", 
                                "Video" : ":/symbols/config/video.png"
                                }
                            
        self.itemDesc = {"General": title0,  
                                "HardDisk": title1, 
                                "CD/DVD-ROM" : title2, 
                                "Floopy" : title3, 
                                "Audio" : title4, 
                                "Network": title5, 
                                "Serial Port" : title6, 
                                "Video" : title7
                                }
        
        self.itemPage = {"General": [self.page_1,  self.displayPage1()] ,  
                                "HardDisk": [self.page_2, self.displayPage2()],   
                                "CD/DVD-ROM" : [self.page_3, self.displayPage3()],  
                                "Floopy" : [self.page_4, self.displayPage4()],  
                                "Audio" : [self.page_5, self.displayPage5()],  
                                "Network": [self.page_6, self.displayPage6()],  
                                "Serial Port" : [self.page_7, self.displayPage7()], 
                                "Video" : [self.page_8,  self.displayPage8()]
                                }
        
        self.initItem(page)
        self.__connectActions()
        
    def __connectActions(self):
        # Menu
        self.connect(self.treeWidget_Menu,  QtCore.SIGNAL("itemClicked(QTreeWidgetItem*,int)"),  self.__action_menuClicked)
        
        # Page1
        self.connect(self.lineEdit_Hostname,  QtCore.SIGNAL("editingFinished()"),  self.__action_ChangeHostname)
        self.connect(self.horizontalSlider_Memory,  QtCore.SIGNAL("valueChanged(int)"),  self.__action_MemoryChangeFromBar)
        self.connect(self.lineEdit_Memory,  QtCore.SIGNAL("textEdited(QString)"),  self.__action_MemoryChangeFromLine)
        self.connect(self.comboBox_isVR,  QtCore.SIGNAL("currentIndexChanged(int)"),  self.__action_ChangeVR)
        self.connect(self.pushButton_CiscoConfig,  QtCore.SIGNAL("clicked()"),  self.__action_CiscoConfig)
        self.connect(self.pushButton_Idlepc,  QtCore.SIGNAL("clicked()"),  self.__action_Idlepc)
        # Page2
        self.connect(self.pushButton_AddHDD,  QtCore.SIGNAL("clicked()"),  self.__action_AddHDD)
        self.connect(self.pushButton_AddHDD2,  QtCore.SIGNAL("clicked()"),  self.__action_AddHDD2)
        #self.connect(self.lineEdit_GeoY,  QtCore.SIGNAL("editingFinished()",  self.__action_ChangeLocation))
        
        # Page3
        self.connect(self.checkBox_MountCD,  QtCore.SIGNAL("stateChanged(int)"),  self.__action_MountCDROM)
        self.connect(self.pushButton_ISOFile,  QtCore.SIGNAL("clicked()"),  self.__action_FindCDROMfile)
        
        # page4: floopy
        self.connect(self.checkBox_Mfloopy,  QtCore.SIGNAL("stateChanged(int)"),  self.__action_MountFloopy)
        self.connect(self.pushButton_ImgFloopy,  QtCore.SIGNAL("clicked()"),  self.__action_FindFloopyfile)
        
        # page6: Network
        self.connect(self.comboBox_Slot,  QtCore.SIGNAL("currentIndexChanged(QString)"),  self.__action_SlotChanged)
        self.connect(self.comboBox_Nic,  QtCore.SIGNAL("currentIndexChanged(int)"),  self.__action_PortChanged)
        self.connect(self.comboBox_Adapter,  QtCore.SIGNAL("currentIndexChanged(QString)"),  self.__action_AdapterChanged)
        self.connect(self.checkBox_EnableNIC,  QtCore.SIGNAL("stateChanged(int)"),  self.__action_EnableNIC)
        self.connect(self.comboBox_Attach,  QtCore.SIGNAL("currentIndexChanged(QString)"),  self.__action_HostIf)
        self.connect(self.comboBox_HostIf,  QtCore.SIGNAL("currentIndexChanged(QString"),  self.__action_Change_HostIf)
        
        # Signal for OK, Cancel
        self.connect(self.buttonBox,  QtCore.SIGNAL('accepted()'),  self.__save )
        #self.connect(self.buttonBox,  QtCore.SIGNAL('rejected()'),  self.close )
        
    # init left menu 
    # page 1: Project
    # page 2: Hypervisors
    def initItem(self,  page):
        
        for item in self.item:
            rootitem = QtGui.QTreeWidgetItem(self.treeWidget_Menu)
            rootitem.setIcon(0,  QtGui.QIcon(self.itemIcon[item]))
            rootitem.setText(0, item)
            self.treeWidget_Menu.insertTopLevelItem(0,  rootitem)
        
        # page seletection
        pageObj = self.itemPage[page]
        self.stackedWidget.setCurrentWidget(pageObj[0])
    
    def __action_menuClicked(self,  item):
        # change detail title
        index = str( item.text(0))
        title = self.itemDesc[index]
        self.lineEdit_Title.setText(title)
        
        # page seletection
        pageObj = self.itemPage[index]
        self.stackedWidget.setCurrentWidget(pageObj[0])
        pageObj[1]
        
    ##########################
    # page1: general
    ##########################
    def displayPage1(self):
        #check virtual
        isVirtual = globals.GApp.topology.nodes[self.pnode.nodeid].isVirtual
        if isVirtual == False:
            self.label_IP.setVisible(True)
            self.lineEdit_IP.setVisible(True)
        else:
            self.label_IP.setVisible(False)
            self.lineEdit_IP.setVisible(False)
        
        
        #######
        # TAB 1
        #######
        # hostname
        self.lineEdit_Hostname.setText(self.pnode.hostname)
        # Model is model of physical node
        self.lineEdit_Model.setText(self.pnode.model)
        
        # hypervisor selection
        hypervisors = globals.GApp.topology.hypervisors
        debug(hypervisors,  "Config Hypervisors")
        # [name, type, uri]
        # selected item
        vmName = globals.GApp.topology.nodes[self.pnode.nodeid].vm
        index = 0
        domainType = None
         
        debug(self.pnode.type,  "domainType")
        if self.pnode.type:
            domainType = self.pnode.type
            
        for item in hypervisors:
            type = item[1]
            debug("Type compare")
            debug(type)
            debug(domainType)
            if type == domainType:
                self.comboBox_Hypervisor.addItem(item[0])
                if vmName == item[0]:
                    self.comboBox_Hypervisor.setCurrentIndex(index)
                index = index + 1
        # set vm
        
        # clock
        count = 0
        for item in self.pnode.clock_list:
            self.comboBox_TIMEZONE.addItem(item)
            if self.pnode.clock == item:
                self.comboBox_TIMEZONE.setCurrentIndex(count)
            count += 1
            
        # Memory
        currentMemory = int(self.pnode.memory)
        cmMB = currentMemory / 1024
        self.lineEdit_Memory.setText(str(cmMB))     
        
        ########
        # TAB 2
        ########
        # is Virtual options
        # can change to real Node
        #
        selections = ["Virtual Node",  "Real Node"]
        for item in selections:
            self.comboBox_isVR.addItem(item)
        vrTF = globals.GApp.topology.nodes[self.pnode.nodeid].isVirtual
        if vrTF == True:
            self.comboBox_isVR.setCurrentIndex(0)
        else:
            self.comboBox_isVR.setCurrentIndex(1)
        
        # Location
        blx = self.pnode.geoX
        bly = self.pnode.geoY
        self.lineEdit_GeoX.setText(str(blx))
        self.lineEdit_GeoY.setText(str(bly))
        lx = self.pnode.posX
        ly = self.pnode.posY
        self.lineEdit_SimX.setText(str(lx))
        self.lineEdit_SimY.setText(str(ly))
        
        #######
        # TAB 3
        #######
        # model check
        if isinstance(self.pnode, Router) == False:
            # remove Advance tab
            self.tabWidget.removeTab(2)
            return
        
        # common console port
        #console = self.pnode.getConsolePort()
        console = self.pnode.devices.console
        self.lineEdit_CiscoConsole.setText(str(console))
        
        if isinstance(self.pnode,  Cisco) == True:
            self.isCisco = True
        else:
            self.isCisco = False
            self.groupBox_Cisco.setDisabled(True)
            return
            
        
        idlepc = self.pnode.idlepc
        if idlepc:
            self.lineEdit_Idlepc.setText(str(idlepc))
        
        # Npe type
        npetype = self.pnode.npetype
        index = 0
        for item in self.pnode.npetype_list:
            self.comboBox_Npetype.addItem(item)
            if npetype == item:
                self.comboBox_Npetype.setCurrentIndex(index)
            index = index + 1
        
        # Mid plane
        midplane = self.pnode.midplane
        index = 0
        for item in self.pnode.midplane_list:
            self.comboBox_Midplane.addItem(item)
            if midplane == item:
                self.comboBox_Midplane.setCurrentIndex(index)
            index = index + 1
            
        # config filename
        filename = self.pnode.cfg
        if filename:
            temp = filename.split("/")
            strfp = temp[-1]
            self.lineEdit_CiscoConfig.setText(str(strfp))
            
    def __action_ChangeHostname(self):
        self.changeSummary = True
        self.changeHostname = True

        
    def __action_ChangeVR(self,  index):
        # VR
        if index == 1:
            self.label_IP.setVisible(True)
            self.lineEdit_IP.setVisible(True)
        else:
            self.label_IP.setVisible(False)
            self.lineEdit_IP.setVisible(False)
            
        self.changeSummary = True
        
    # save page
    def displayPage1_save(self):
        # TAB1
        self.pnode.hostname = str( self.lineEdit_Hostname.text() )
        self.pnode.model = str( self.lineEdit_Model.text() )
        self.pnode.clock = str( self.comboBox_TIMEZONE.currentText() )
        memory = int(self.lineEdit_Memory.text())
        self.pnode.memory = str( memory * 1024)
        globals.GApp.topology.nodes[self.pnode.nodeid].vm = str( self.comboBox_Hypervisor.currentText() )
        
        # TAB2
        tf = True
        if str(self.comboBox_isVR.currentText()) == "Real Node":
            # change to Real Node
            tf = False
            # update node state
            self.pnode.state = globals.UNKNOWN
            
        globals.GApp.topology.nodes[self.pnode.nodeid].isVirtual = tf
        # GeoX, GeoY
        self.pnode.geoX = str( self.lineEdit_GeoX.text() )
        self.pnode.geoY = str( self.lineEdit_GeoY.text() )
        self.pnode.posX = str( self.lineEdit_SimX.text() )
        self.pnode.posY = str( self.lineEdit_SimY.text() )
        
        # TAB3
        if self.isCisco == True:
            self.pnode.console = str( self.lineEdit_CiscoConsole.text() )
            idlepc = str( self.lineEdit_Idlepc.text() )
            if idlepc:
                self.pnode.idlepc = idlepc
            self.pnode.npetype = str( self.comboBox_Npetype.currentText() )
            self.pnode.midplane = str( self.comboBox_Midplane.currentText() )
            #cfg = str( self.lineEdit_CiscoConfig.text() )
            #if cfg:
            #    self.pnode.cfg = cfg
               
        
        
        
        
    # Memory action
    def __action_MemoryChangeFromBar(self,  value):
        self.lineEdit_Memory.setText(str(value))
        
    def __action_MemoryChangeFromLine(self,  mb):
        value = str(mb)
        valueMB = int(value) 
        self.horizontalSlider_Memory.setSliderPosition(valueMB)
        
    def __action_CiscoConfig(self):
        filename = None
        cfg = RemoteFolder(filename,  self.pnode.nodeid)
        cfg.show()
        if cfg.exec_():
            filename = cfg.selectedfile
            
        # choose local filename
        #filename = QtGui.QFileDialog.getOpenFileName(self, "Choose Cisco Config",  "", "Config files (*.cfg);;All files (*.*)")
        if filename:
            temp = filename.split("/")
            strfp = temp[-1]
            self.lineEdit_CiscoConfig.setText(str(strfp))
            self.pnode.cfg = str(filename)
        
    def __action_Idlepc(self):
        """ get Idlepc and set it automatically
        """
        msg = "Get Idlepc value from router"
        node_state = self.pnode.state
        if node_state != globals.START:
            msg = "idlepc value can get, when the node is running"
            message(msg,  "warning")
            return False
        
        # get idlepc
        values = self.pnode.getIdlepc()
        print values
        min = 100
        idlepc = ""
        for item in values:
            index = item.split(" ")
            cpu = (re.search("\d+",  index[2])).group()
            if int(cpu) < min:
                min = int(cpu)
                idlepc = index[1]
        
        print (min,  idlepc)
        # update Config windows
        node = globals.GApp.topology.nodes[self.pnode.nodeid]
        node.physnode.idlepc = idlepc
        #self.pnode.idlepc = idlepc
        #self.lineEdit_Idlepc.setText(idlepc)
        
        # call setIdlepc for router
        self.pnode.setIdlepc(idlepc)
        
        
    ##########################
    # page2: hdd
    ##########################
    def displayPage2(self):
        self.__hddFile = None
        # Header Label
        items = ["Name",  "Size (GB)"]
        self.tableWidget_HDD.setColumnWidth(0,  200)
        self.tableWidget_HDD.setColumnWidth(1,  123)
        self.tableWidget_HDD.setHorizontalHeaderLabels(items)
        
        # check model
        # filename always exist, because deault setting exists
        filename = self.pnode.devices.hdd.source
        
        self.__hddFile = filename
        rfsGB = "unknown"
        if os.path.isfile(filename):
            filesize = os.path.getsize(filename)
            fsGB = long(filesize)/ (1024*1024*1024.0)
            rfsGB = round(fsGB,  3) #round number
            
        strIndex = filename.split("/")
            
        item1 = QtGui.QTableWidgetItem(str(strIndex[-1]))
        item2 = QtGui.QTableWidgetItem(str(rfsGB))
        item1.setTextAlignment(0x84)
        item2.setTextAlignment(0x84)
        self.tableWidget_HDD.setItem(0, 0,  item1)
        self.tableWidget_HDD.setItem(0,  1,  item2)
        
            

        
       
    
    def __action_AddHDD(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, "Choose HDD Image",  "", "All files (*.*)")
        
        if filename:
            self.__hddFile = str(filename)
            filesize = os.path.getsize(filename)
            fsGB = long(filesize)/ (1024*1024*1024.0)
            rfsGB = round(fsGB,  3) #round number
            strIndex = filename.split("/")
            print strIndex[-1]
            
            item1 = QtGui.QTableWidgetItem(str(strIndex[-1]))
            item2 = QtGui.QTableWidgetItem(str(rfsGB))
            item1.setTextAlignment(0x84)
            item2.setTextAlignment(0x84)
            self.tableWidget_HDD.setItem(0, 0,  item1)
            self.tableWidget_HDD.setItem(0,  1,  item2)
            
    def __action_AddHDD2(self):
        # open RemoteFolder
        filename = ""
        cfg = RemoteFolder(filename,  self.pnode.nodeid)
        cfg.show()
        if cfg.exec_():
            filename = cfg.selectedfile
        
        #msg = "Choose Disk Image"
        #(filename,  ok) = QtGui.QInputDialog.getText(globals.GApp.mainWindow,  "Choose Disk Image",  msg,  QtGui.QLineEdit.Normal,  "/data/testbed/c7200.bin")
        print filename
        if filename:
            self.__hddFile = str(filename)
            rfsGB = "Unknown"
            strIndex = filename.split("/")
            print strIndex[-1]
            
            item1 = QtGui.QTableWidgetItem(str(strIndex[-1]))
            item2 = QtGui.QTableWidgetItem(str(rfsGB))
            item1.setTextAlignment(0x84)
            item2.setTextAlignment(0x84)
            self.tableWidget_HDD.setItem(0, 0,  item1)
            self.tableWidget_HDD.setItem(0,  1,  item2)
   
    def displayPage2_save(self):
        """ save hdd image file
        """
        self.pnode.devices.hdd.source = str(self.__hddFile)
        
     
    ##############################
    # page3 : CDROM
    ##############################
    def displayPage3(self):
        # Cisco has no CDROM        
        if self.isCisco == True:
            self.checkBox_MountCD.setDisabled(True)
            self.radioButton_HostCD.setDisabled(True)
            self.radioButton_ISOfile.setDisabled(True)
            self.pushButton_ISOFile.setDisabled(True)
            return
        
        if self.pnode.devices.hasCDROM == False:
            self.checkBox_MountCD.setChecked(False)
            return
            
        # has cdrom driver
        self.checkBox_MountCD.setChecked(True)
        # find type
        type = self.pnode.devices.cdrom.type
        self.__cdromfile = self.pnode.devices.cdrom.source
        if self.__cdromfile == None:
            return
            
        if type == "block":
            self.radioButton_HostCD.setChecked(True)
        else:
            # file node
            self.radioButton_ISOfile.setChecked(True)
            strfile = self.__cdromfile.split("/")
            self.comboBox_CDISO.addItem(strfile[-1]) 
        
     
    def __action_MountCDROM(self,  int):
        # checkbox
        tf = self.checkBox_MountCD.isChecked()
        
        if tf == False:
            # disable all
            self.radioButton_HostCD.setDisabled(True)
            self.radioButton_ISOfile.setDisabled(True)
            self.pushButton_ISOFile.setDisabled(True)
        else:
            self.radioButton_HostCD.setDisabled(False)
            self.radioButton_ISOfile.setDisabled(False)
            self.pushButton_ISOFile.setDisabled(False)
     
    def __action_FindCDROMfile(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, "Choose CD/DVD-ROM Image",  "", "ISO files (*.iso) ;; All files (*.*)")   
        
        if filename:
            self.__cdromfile = str(filename)
            strfp = self.__cdromfile.split("/")
            self.comboBox_CDISO.addItem(strfp[-1])
            
            
    def displayPage3_save(self):
        if self.isCisco == True:
            return
        # QEMU
        tf = self.checkBox_MountCD.isChecked()
        if tf == False:
            self.pnode.devices.hasCDROM = False
            return
         
        if self.radioButton_ISOfile.isChecked() == True:
            self.pnode.devices.hasCDROM = True
            self.pnode.devices.cdrom.source = str( self.__cdromfile)
        else:
            # HOST devices
            pass
        
    #########################
    # page 4: floopy
    #########################
    def displayPage4(self):
        # Cisco has no  floopy
        if self.isCisco == True:
            self.checkBox_Mfloopy.setDisabled(True)
            self.radioButton_HostFloopy.setDisabled(True)
            self.radioButton_ImgFloopy.setDisabled(True)
            self.pushButton_ImgFloopy.setDisabled(True)
            return
        
        if self.pnode.devices.hasFloopy == False:
            self.checkBox_Mfloopy.setChecked(False)
            return
            
        # has floopy driver
        self.checkBox_Mfloopy.setChecked(True)
        # find type
        type = self.pnode.devices.floopy.type
        self.__floopyfile = self.pnode.devices.floopy.source
        if self.__floopyfile == None:
            return
            
        if type == "block":
            self.radioButton_HostFloopy.setChecked(True)
        else:
            # file node
            self.radioButton_ImgFloopy.setChecked(True)
            strfile = self.__floopyfile.split("/")
            self.comboBox_ImgFloopy.addItem(strfile[-1]) 
 
    def __action_MountFloopy(self,  int):
        # checkbox
        tf = self.checkBox_Mfloopy.isChecked()
        
        if tf == False:
            # disable all
            self.radioButton_HostFloopy.setDisabled(True)
            self.radioButton_ImgFloopy.setDisabled(True)
            self.pushButton_ImgFloopy.setDisabled(True)
        else:
            self.radioButton_HostFloopy.setDisabled(False)
            self.radioButton_ImgFloopy.setDisabled(False)
            self.pushButton_ImgFloopy.setDisabled(False)


    def __action_FindFloopyfile(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, "Choose Floopy Image",  "", "ISO files (*.iso) ;; All files (*.*)")   
        
        if filename:
            self.__floopyfile = str(filename)
            strfp = self.__floopyfile.split("/")
            self.comboBox_ImgFloopy.addItem(strfp[-1])
     
    def displayPage4_save(self):
        if self.isCisco == True:
            return
        # QEMU
        tf = self.checkBox_Mfloopy.isChecked()
        if tf == False:
            self.pnode.devices.hasFloopy = False
            return
         
        if self.radioButton_ImgFloopy.isChecked() == True:
            self.pnode.devices.hasFloopy = True
            self.pnode.devices.floopy.source = str( self.__floopyfile)
        else:
            # HOST devices
            pass
            
    #############################
    # Page 5: AUDIO
    #############################
    def displayPage5(self):
        # Cisco has no CDROM        
        if self.isCisco == True:
            self.checkBox_EnAudio.setDisabled(True)
            self.comboBox_AController.setDisabled(True)
            self.comboBox_HAdriver.setDisabled(True)
            self.label_AController.setDisabled(True)
            self.label_HAdriver.setDisabled(True)
            return
        pass
        
    ##########################
    # Network Interface
    ##########################
    def displayPage6(self):
        # initial
        self.adapterLock = False
        # NIC
        slot = self.pnode.devices.slot
        
        slotKey = slot.keys()
        slotKey.sort()
        # show slot
        for slotName in slotKey:
            self.comboBox_Slot.addItem(slotName)
        
        # find first interface (slot 0, port 0)
        self.selectedSlot = 'slot 0'
        port0 = slot[self.selectedSlot]
        interface0 = port0[0]
        
        # ports
        port_list = self.pnode.devices.getPossiblePorts('slot 0')
        self.showPossiblePort(port_list)
        self.showNicDetail(interface0)
        
        self.currentInterface = interface0
           
        
    def showNicDetail(self,  interface,  chAdapter=True):
        #  enable NIC
        self.checkBox_EnableNIC.setChecked(interface.isEnabled)
       
        # enable or disable by isAssigned value
        showList = [self.comboBox_Adapter,  self.comboBox_Attach,  self.lineEdit_MAC,  self.pushButton_Generate]
        show = False
        if interface.isEnabled == False:
            show=True
        
        for item in showList:
            item.setDisabled(show)
        
        # adapter
        if chAdapter == True:
            pAdapter = interface.getPossibleAdapter()
            self.comboBox_Adapter.clear()
            count = 0
            for item in pAdapter:
                self.adapterLock = True
                self.comboBox_Adapter.addItem(item)
                if item == interface.adapter:
                    self.comboBox_Adapter.setCurrentIndex(count)
                count = count + 1
        
        # attach
        self.comboBox_Attach.clear()
        count = 0
        for item in interface.type_list:
            self.comboBox_Attach.addItem(item)
            if item == interface.type:
                self.comboBox_Attach.setCurrentIndex(count)
            count = count + 1
        
        # disable for change type if IF is assigned & enabled
        if interface.isAssigned and interface.isEnabled:
            self.comboBox_Attach.setDisabled(True)
        else:
            self.comboBox_Attach.setDisabled(False)
            
        # If host interface
        if interface.type == "Internal":
            self.comboBox_HostIf.hide()
        else:
            self.comboBox_HostIf.show()
            
        # MAC
        self.lineEdit_MAC.setText(interface.mac)
        self.adapterLock = False
    
    def showPossiblePort(self,  ports,  focus=0):
        #self.lockPort = True
        self.comboBox_Nic.clear()
        for item in ports:
            self.comboBox_Nic.addItem(item)
        # focus index
        self.comboBox_Nic.setCurrentIndex(focus)
    
    def showPossibleAdapter(self,  adapters,  focusText=None):
        self.comboBox_Adapter.clear()
        focus = 0
        index = 0
        for item in adapters:
            if focusText == item:
                focus = index
            self.comboBox_Adapter.addItem(item)
            index = index + 1
        # focus index
        self.comboBox_Adapter.setCurrentIndex(focus)
        
    def __action_SlotChanged(self,  sname):
        """ change port name
        based on slot change
        """
        debug(sname,  "Config:slotchanged")
        slotName = str(sname)
        self.selectedSlot = slotName
        temp = slotName.split(" ")
        slotNumber = temp[1]
        
        # find adapter
        adapterList = self.pnode.devices.getPossibleAdapter(slotNumber)
        debug(adapterList,  "adapterList")
        ports = self.pnode.devices.slot[slotName]
        adapter = ports["adapter"]
        print adapter[0],  adapter[1]
        self.showPossibleAdapter(adapterList,  adapter[0])
        
        #self.comboBox_Adapter.setCurrentText(adapter[0])
        
        # update port name
        
        port_list = self.pnode.devices.getPossiblePorts(slotName)
        debug(port_list,  "Port List")
        self.showPossiblePort(port_list)
        
        # show port0 information
        interface = ports[0]
        print "interface assigned:",  interface.isAssigned,  interface.name,  interface.adapter
        self.showNicDetail(interface,  False)
        
        
        
    def __action_PortChanged(self,  pindex):
        """ change interface contents
        based on port change
        """
        """
        if self.lockPort == True:
            self.lockPort == False
            return
        """
        if pindex < 0:
            return
        ports = self.pnode.devices.slot[str(self.selectedSlot)]
        
        interface = ports[int(pindex)]
        self.currentInterface = interface
        self.showNicDetail(interface,  chAdapter=False)
        
    def __action_AdapterChanged(self,  aname):
        # find possible port names
        debug("Adapter Changed")
        debug(aname)
        if self.adapterLock == True:
            debug("adapterLocked")
            self.adapterLock = False
            return
            
        if not aname:
            debug("adapter name is not exist")
            return
            
        debug(self.selectedSlot,  "Adapter Changed: slected slot")
        adapterName = str(aname)
        ports = self.pnode.devices.slot[str(self.selectedSlot)]
        # display interface information
        
        # get adapter information
        # adapter name, max interface
        dic = self.pnode.devices.getPossibleAdapter(self.selectedSlot)
        debug(dic,  "PossibleAdapter Dictionary")
        maxInterface = dic[adapterName]
        
        # update adapter information in self.slot
        adapter = ports["adapter"]
        adapter[0] = adapterName
        adapter[1] = maxInterface
        
        # change all adapter in slot
        # change comboBox_Port
        self.comboBox_Nic.clear()
        for i in range(maxInterface):
            interface = ports[i]
            interface.changeAdapter(adapterName)
            # interface name is changed
            self.comboBox_Nic.addItem(interface.name)
        
            
    def __action_EnableNIC(self,  value):
        """ Change Interface state
        """
        if self.checkBox_EnableNIC.isChecked() == True:
            # update current interface
            self.currentInterface.isEnabled = True
            # change every element's state to enabled
            count = self.comboBox_Nic.count()
            #debug("count: %s" % count)
            for i in range(count):
                interfaceName = self.comboBox_Nic.itemText(i)
                ports = self.pnode.devices.slot[str(self.selectedSlot)]
                interface = ports[i]
                interface.setEnabled(True)
            
        else:
            self.currentInterface.isEnabled = False
        
        #self.pnode.devices.setIFAssigned(self.currentInterface.slot,  self.currentInterface.port,  self.currentInterface.isAssigned)
        self.showNicDetail(self.currentInterface,  chAdapter=False)
        
    def __action_HostIf(self,  type):
        """ view host Interface connection
        """
        if str(type) == "Host":
            self.currentInterface.type = "Host"
            self.comboBox_HostIf.show()
            hostNicList = ["eth0",  "eth1", "tap0", "tap1", "tap2"]
            self.comboBox_HostIf.clear()
            for item in hostNicList:
                self.comboBox_HostIf.addItem(item)
           
        elif str(type) == "Bridge":
            self.currentInterface.type = "Bridge"
            self.comboBox_HostIf.show()
            hostNicList = ["tap0", "tap1", "vnet0", "vnet1"]
            self.comboBox_HostIf.clear()
            for item in hostNicList:
                self.comboBox_HostIf.addItem(item)
        else:
            # internal
            self.comboBox_HostIf.hide()
                
    def __action_Change_HostIf(self,  type):
        self.currentIndex.HostIfName = str(type)
        
    def displayPage7(self):
        pass
    def displayPage8(self):
        pass
   
    
    def __save(self):
        # check node state
        # if node is running, donot save
        if self.pnode.state == globals.START:
            msg = "Can not save configuration, when the node is running"
            message(msg,  "critical")
            return False
        
        # update pnode information
        self.displayPage1_save()
        self.displayPage2_save()
        self.displayPage3_save()
        #self.displayPage6_save()   # Network Information
        
        # if the state of node is running
        # can not save
        if self.pnode.state == globals.START or self.pnode.state == globals.SUSPEND:
            message("Can not save a config, when a node is running")
            return False
        
        # delete old object
        del globals.GApp.topology.nodes[self.pnode.nodeid].physnode
        # copy new object
        globals.GApp.topology.nodes[self.pnode.nodeid].physnode = self.pnode
        # close
        
        if self.changeSummary == True:
            globals.GApp.mainWindow.NodesSummary.refresh()
            
        print self.changeHostname
        if self.changeHostname == True:
            guiinfo = globals.GApp.topology.nodes[self.pnode.nodeid].guiinfo
            guiinfo.updateHostname(self.pnode.hostname)
            
        return True
